require 'appengine-apis/users'

## 使わないかも
def login_require(redirect_to_url = '/')
  if AppEngine::Users.logged_in?
    google_user = AppEngine::Users.current_user
    @user = User.first(:email => google_user.email)
    if @user.nil?
      @user = User.create(
        :name => google_user.nickname,
        :email => google_user.email,
        :domain => google_user.auth_domain,
        :created_at => Time.now
      )
    end
  else
    # check Basic-Auth
    need_to_redirect = true
    use Rack::Auth::Basic do |username, password|
      @user = User.first(:email => username, :password => password)
      need_to_redirect = false unless @user.nil?
    end
    if need_to_redirect
      redirect AppEngine::Users.create_login_url(redirect_to_url)
    end
  end
end

# 人間様用
def google_login_require(redirect_to_url = '/')
  if AppEngine::Users.logged_in?
    google_user = AppEngine::Users.current_user
    @user = User.first(:email => google_user.email)
    if @user.nil?
      @user = User.create(
        :name => google_user.nickname,
        :email => google_user.email,
        :domain => google_user.auth_domain,
        :created_at => Time.now
      )
    end
  else
    redirect AppEngine::Users.create_login_url(redirect_to_url)
  end
end

# Android様用
def basic_auth_require(error_message = 'Check your ID and password!')
  @logger.debug "enter basic_auth"

  @auth ||=  Rack::Auth::Basic::Request.new(request.env)
  if @auth.provided? and @auth.basic? and @auth.credentials
    username = @auth.credentials[0]
    password = @auth.credentials[1]
    @logger.debug "input username: #{username} / password: #{password}"
    @user = User.first(:email => username, :password => password)
  end

# 何故か使えない…
#  use Rack::Auth::Basic do |username, password|
#    @logger.debug "input username: #{username} / password: #{password}"
#    @user = User.first(:email => username, :password => password)
#  end
  @logger.debug "pass basic_auth"

  if @user.nil?
    response.header["WWW-Authenticate"] = 'Basic realm="' + error_message + '"'
    halt 401, error_message
  end
end

def setup_logger
  @logger = AppEngine::Logger.new
end

def google_logout(path)
  AppEngine::Users.create_logout_url(path)
end

